<template>
  <div class="common-container">
    <div class="common-header">
      <h2>智能分析</h2>
    </div>
    
    <!-- 预警提示区域 -->
    <div class="alert-section" v-if="alerts.length > 0">
      <el-alert
        v-for="alert in visibleAlerts"
        :key="alert.type"
        :title="alert.message"
        :type="alert.level === 'DANGER' ? 'error' : 'warning'"
        :closable="true"
        show-icon
        class="alert-item"
        @close="dismissAlert(alert.type)"
      />
    </div>
    
    <!-- 数据概览卡片 -->
    <div class="overview-cards">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="overview-card">
            <div class="card-header">
              <span>近30天新增客户</span>
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="card-content">
              <div class="big-number">{{ totalNewCustomers }}</div>
              <div class="sub-text">总计新增</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="overview-card">
            <div class="card-header">
              <span>高价值客户</span>
              <el-icon><Star /></el-icon>
            </div>
            <div class="card-content">
              <div class="big-number">{{ highValueCustomerCount }}</div>
              <div class="sub-text">活跃客户</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="overview-card">
            <div class="card-header">
              <span>互动热度</span>
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="card-content">
              <div class="big-number">{{ averageInteractions }}</div>
              <div class="sub-text">平均互动次数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 客户趋势图表 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>近30日新增客户趋势</span>
          <el-button 
            type="text" 
            @click="refreshTrendData"
            :loading="trendLoading"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>
      <div id="customer-trend-chart" style="width: 100%; height: 400px;"></div>
    </el-card>
    
    <!-- 高价值客户列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>高价值客户列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索客户姓名或公司"
              style="width: 200px; margin-right: 10px;"
              @keyup.enter="searchHighValueCustomers"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="searchHighValueCustomers">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button type="success" @click="exportData" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="highValueCustomers" 
        style="width: 100%;"
        v-loading="tableLoading"
        :height="tableHeight"
      >
        <el-table-column prop="customerName" label="客户姓名" min-width="120" />
        <el-table-column prop="companyName" label="公司名称" min-width="150" />
        <el-table-column prop="customerStatus" label="客户状态" width="120">
          <template #default="scope">
            <el-tag 
              :type="getStatusTagType(scope.row.customerStatus)"
            >
              {{ scope.row.customerStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="interactionCount" label="互动次数" width="100">
          <template #default="scope">
            <el-badge 
              :value="scope.row.interactionCount" 
              :type="getInteractionBadgeType(scope.row.interactionCount)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="lastContactTime" label="上次联系时间" width="180">
          <template #default="scope">
            {{ scope.row.lastContactTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="viewCustomerDetail(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="common-pagination">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          small
        />
      </div>
    </el-card>
    
    <!-- 客户详情对话框 -->
    <el-dialog 
      title="客户详情" 
      v-model="detailDialogVisible" 
      width="600px"
    >
      <div v-if="selectedCustomer">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="客户姓名">
            {{ selectedCustomer.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            {{ selectedCustomer.companyName }}
          </el-descriptions-item>
          <el-descriptions-item label="客户状态">
            <el-tag :type="getStatusTagType(selectedCustomer.customerStatus)">
              {{ selectedCustomer.customerStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="互动次数">
            <el-badge 
              :value="selectedCustomer.interactionCount" 
              :type="getInteractionBadgeType(selectedCustomer.interactionCount)"
            />
          </el-descriptions-item>
          <el-descriptions-item label="上次联系时间" :span="2">
            {{ selectedCustomer.lastContactTime || '暂无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="common-dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="goToCustomerManagement">
            前往客户管理
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 客户趋势详情对话框 -->
    <el-dialog 
      :title="trendDetailTitle" 
      v-model="trendDetailDialogVisible" 
      width="800px"
      top="5vh"
    >
      <div class="trend-detail-header">
        <el-statistic
          title="新增客户数量"
          :value="selectedDateCustomers.length"
          suffix="人"
        >
          <template #prefix>
            <el-icon style="vertical-align: -0.125em">
              <User />
            </el-icon>
          </template>
        </el-statistic>
      </div>
      
      <el-divider />
      
      <div class="customer-grid" v-if="selectedDateCustomers.length > 0">
        <div 
          v-for="(customer, index) in selectedDateCustomers" 
          :key="index"
          class="customer-card"
          @click="viewTrendCustomerDetail(customer)"
        >
          <div class="customer-avatar">
            <el-avatar 
              :size="40" 
              :style="{backgroundColor: getAvatarColor(customer.name)}"
            >
              {{ customer.name.charAt(0) }}
            </el-avatar>
          </div>
          <div class="customer-info">
            <div class="customer-name">{{ customer.name }}</div>
            <div class="customer-company">{{ customer.companyName }}</div>
            <div class="customer-status">
              <el-tag 
                size="small" 
                :type="getStatusTagType(customer.status)"
              >
                {{ customer.status }}
              </el-tag>
            </div>
          </div>
          <div class="customer-actions">
            <el-button 
              type="text" 
              size="small" 
              @click.stop="goToCustomerDetail(customer)"
            >
              <el-icon><View /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
      
      <el-empty 
        v-else 
        description="当日无新增客户"
        :image-size="100"
      />
      
      <template #footer>
        <span class="common-dialog-footer">
          <el-button @click="trendDetailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="goToCustomerManagement">
            前往客户管理
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  TrendCharts, 
  Star, 
  ChatDotRound, 
  Refresh, 
  Search, 
  Download,
  User,
  View
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { 
  getAnalysisAlerts,
  getCustomerTrendData,
  getHighValueCustomers,
  exportHighValueCustomers
} from '../utils/api'

export default {
  name: 'AnalysisManagement',
  components: {
    TrendCharts,
    Star,
    ChatDotRound,
    Refresh,
    Search,
    Download,
    User,
    View
  },
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const alerts = ref([])
    const dismissedAlerts = ref(new Set())
    const trendData = ref([])
    const highValueCustomers = ref([])
    const selectedCustomer = ref(null)
    
    // 加载状态
    const trendLoading = ref(false)
    const tableLoading = ref(false)
    const exportLoading = ref(false)
    
    // 对话框状态
    const detailDialogVisible = ref(false)
    const trendDetailDialogVisible = ref(false)
    
    // 选中的数据
    const selectedDateCustomers = ref([])
    const selectedDate = ref('')
    
    // 搜索和分页
    const searchKeyword = ref('')
    const pagination = ref({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 图表实例
    let chartInstance = null
    
    // 计算属性
    const visibleAlerts = computed(() => {
      return alerts.value.filter(alert => !dismissedAlerts.value.has(alert.type))
    })
    
    const totalNewCustomers = computed(() => {
      return trendData.value.reduce((sum, item) => sum + item.count, 0)
    })
    
    const highValueCustomerCount = computed(() => {
      return pagination.value.total
    })
    
    const averageInteractions = computed(() => {
      if (highValueCustomers.value.length === 0) return 0
      const total = highValueCustomers.value.reduce(
        (sum, customer) => sum + customer.interactionCount, 0
      )
      return Math.round(total / highValueCustomers.value.length * 10) / 10
    })
    
    const trendDetailTitle = computed(() => {
      return `${selectedDate.value} 新增客户详情`
    })
    
    // 方法
    const loadAlerts = async () => {
      try {
        const response = await getAnalysisAlerts()
        if (response.data.code === 200) {
          alerts.value = response.data.data || []
        }
      } catch (error) {
        console.error('加载预警信息失败:', error)
      }
    }
    
    const loadTrendData = async () => {
      trendLoading.value = true
      try {
        const response = await getCustomerTrendData()
        if (response.data.code === 200) {
          trendData.value = response.data.data || []
          await nextTick()
          renderChart()
        }
      } catch (error) {
        ElMessage.error('加载趋势数据失败')
      } finally {
        trendLoading.value = false
      }
    }
    
    const loadHighValueCustomers = async () => {
      tableLoading.value = true
      try {
        const params = {
          page: pagination.value.page,
          size: pagination.value.size
        }
        if (searchKeyword.value) {
          params.keyword = searchKeyword.value
        }
        
        const response = await getHighValueCustomers(params)
        if (response.data.code === 200) {
          const data = response.data.data
          highValueCustomers.value = data.records || []
          pagination.value.total = data.total || 0
        }
      } catch (error) {
        ElMessage.error('加载高价值客户失败')
      } finally {
        tableLoading.value = false
      }
    }
    
    const renderChart = () => {
      const chartDom = document.getElementById('customer-trend-chart')
      if (!chartDom) return
      
      if (chartInstance) {
        chartInstance.dispose()
      }
      
      chartInstance = echarts.init(chartDom)
      
      const dates = trendData.value.map(item => item.date)
      const counts = trendData.value.map(item => item.count)
      
      const option = {
        title: {
          text: '客户新增趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            const dataIndex = params[0].dataIndex
            const item = trendData.value[dataIndex]
            let content = `日期: ${item.date}<br/>新增客户: ${item.count}人`
            if (item.customers && item.customers.length > 0) {
              content += '<br/>客户列表:<br/>'
              item.customers.forEach(customer => {
                content += `• ${customer.name} (${customer.companyName})<br/>`
              })
            }
            return content
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '新增客户',
            type: 'line',
            stack: 'Total',
            data: counts,
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(64, 158, 255, 0.6)'
                }, {
                  offset: 1, color: 'rgba(64, 158, 255, 0.1)'
                }]
              }
            },
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      
      chartInstance.setOption(option)
      
      // 点击事件
      chartInstance.on('click', function(params) {
        const item = trendData.value[params.dataIndex]
        if (item.customers && item.customers.length > 0) {
          showCustomerList(item.date, item.customers)
        } else {
          ElMessage.info(`${item.date} 当日无新增客户`)
        }
      })
    }
    
    const showCustomerList = (date, customers) => {
      selectedDate.value = date
      selectedDateCustomers.value = customers
      trendDetailDialogVisible.value = true
    }
    
    const dismissAlert = (alertType) => {
      dismissedAlerts.value.add(alertType)
    }
    
    const refreshTrendData = () => {
      loadTrendData()
    }
    
    const searchHighValueCustomers = () => {
      pagination.value.page = 1
      loadHighValueCustomers()
    }
    
    const handleSizeChange = (newSize) => {
      pagination.value.size = newSize
      pagination.value.page = 1
      loadHighValueCustomers()
    }
    
    const handleCurrentChange = (newPage) => {
      pagination.value.page = newPage
      loadHighValueCustomers()
    }
    
    const viewCustomerDetail = (customer) => {
      selectedCustomer.value = customer
      detailDialogVisible.value = true
    }
    
    const goToCustomerManagement = () => {
      detailDialogVisible.value = false
      router.push('/customer-management')
    }
    
    const exportData = async () => {
      exportLoading.value = true
      try {
        const params = {}
        if (searchKeyword.value) {
          params.keyword = searchKeyword.value
        }
        
        const response = await exportHighValueCustomers(params)
        if (response.data.code === 200) {
          // 这里可以实现真正的文件下载，暂时用消息提示
          ElMessage.success(`导出成功，共 ${response.data.data.length} 条记录`)
          console.log('导出数据:', response.data.data)
        }
      } catch (error) {
        ElMessage.error('导出失败')
      } finally {
        exportLoading.value = false
      }
    }
    
    const getStatusTagType = (status) => {
      switch (status) {
        case '潜在客户': return ''
        case '已联系客户': return 'success'
        case '已流失': return 'danger'
        default: return 'info'
      }
    }
    
    const getInteractionBadgeType = (count) => {
      if (count >= 5) return 'danger'
      if (count >= 3) return 'warning'
      return 'primary'
    }
    
    const getAvatarColor = (name) => {
      const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
      const index = name.charCodeAt(0) % colors.length
      return colors[index]
    }
    
    const viewTrendCustomerDetail = (customer) => {
      // 可以在这里实现查看客户详情的逻辑
      console.log('查看客户详情:', customer)
    }
    
    const goToCustomerDetail = (customer) => {
      // 跳转到客户管理页面并定位到特定客户
      router.push(`/customer-management?customerId=${customer.id}`)
    }
    
    // 生命周期
    onMounted(() => {
      loadAlerts()
      loadTrendData()
      loadHighValueCustomers()
    })
    
    return {
      alerts,
      visibleAlerts,
      trendData,
      highValueCustomers,
      selectedCustomer,
      selectedDateCustomers,
      selectedDate,
      trendLoading,
      tableLoading,
      exportLoading,
      detailDialogVisible,
      trendDetailDialogVisible,
      searchKeyword,
      pagination,
      totalNewCustomers,
      highValueCustomerCount,
      averageInteractions,
      trendDetailTitle,
      dismissAlert,
      refreshTrendData,
      searchHighValueCustomers,
      handleSizeChange,
      handleCurrentChange,
      viewCustomerDetail,
      goToCustomerManagement,
      exportData,
      getStatusTagType,
      getInteractionBadgeType,
      getAvatarColor,
      viewTrendCustomerDetail,
      goToCustomerDetail
    }
  }
}
</script>

<style scoped>


.alert-section {
  margin-bottom: 20px;
}

.alert-item {
  margin-bottom: 10px;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  text-align: center;
}

.overview-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #909399;
  margin-bottom: 20px;
}

.overview-card .card-content {
  padding: 10px 0;
}

.overview-card .big-number {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.overview-card .sub-text {
  font-size: 12px;
  color: #909399;
}

.chart-card, .table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.trend-detail-header {
  text-align: center;
  margin-bottom: 20px;
}

.customer-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.customer-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  background: #FFFFFF;
  cursor: pointer;
  transition: all 0.3s ease;
}

.customer-card:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.customer-avatar {
  margin-right: 12px;
}

.customer-info {
  flex: 1;
  min-width: 0;
}

.customer-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.customer-company {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.customer-status {
  margin-bottom: 0;
}

.customer-actions {
  margin-left: 8px;
}
</style>